package com.star.sync.elasticsearch.config;

import com.google.common.base.Splitter;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author <a href="mailto:wangchao.star@gmail.com">wangchao</a>
 * @version 1.0
 * @since 2017-08-25 17:32:00
 */
@Configuration
public class ElasticsearchConfig implements DisposableBean {

    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchConfig.class);
    /**
     * es集群节点,格式为=>ip1:port1,ip2:port2...
     * 默认为本地es
     */
    @Value(value = "${es.cluster.nodes:127.0.0.1:9300}")
    private String esClusterNodes;

    /**
     * es集群名称
     */
    @Value(value = "${es.cluster.name:elasticsearch}")
    private String esClusterName;

    /**
     * es所有操作的超时时间,单位秒
     */
    @Value(value = "${es.operate.timeout:10}")
    private int esOperateTimeoutSeconds;

    /**
     * es transport client
     */
    private TransportClient client;

    public static long defaultTimeout;

    @Bean("transportClient")
    public TransportClient getTransportClient() {
        if (client == null) {
            // 以transport方式连接es
            Settings settings =  Settings.builder().put("cluster.name", esClusterName)
                    // 自动嗅探其他es节点
                    .put("client.transport.sniff", true)
                    .put("client.transport.ignore_cluster_name", false)
                    .put("client.transport.ping_timeout", "5s")
                    .put("client.transport.nodes_sampler_interval", "5s").build();

            client=   new PreBuiltTransportClient(settings);

            Map<String, String> nodes = Splitter.on(',')
                    .trimResults()
                    .omitEmptyStrings()
                    .withKeyValueSeparator(':')
                    .split(esClusterNodes);
            if (nodes.isEmpty()) {
                throw new IllegalArgumentException("clusterNodes格式不正确！要求ip1:port1,ip2:port2");
            }
            for (Map.Entry<String, String> entry : nodes.entrySet()) {
                String host = entry.getKey();
                int port = Integer.parseInt(entry.getValue());

                try {
                    client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
                } catch (UnknownHostException e) {
                    logger.info("无法连接服务器："+e.getMessage());
                }

            }
            if (esOperateTimeoutSeconds <= 0) {
                esOperateTimeoutSeconds = 10;
            }
            defaultTimeout = TimeUnit.SECONDS.toMillis(esOperateTimeoutSeconds);
        }
        return client;
    }

    @Override
    public void destroy() throws Exception {
        if (client != null) {
            client.close();
        }
    }

}
